﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MSGGolbalInfo;

namespace UserLoginTest
{
    public partial class Form1 : common.frmBase
    {
        public Form1()
        #region >><<
        {
            InitializeComponent();
            AppName = "UserLoginServer";    
     
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            ExitAPP();
        }
        #endregion

        private void LoadMSG()
        #region >><<
        {
           
        }

        protected void print(string msg)
        {
            this.Invoke(new Action(() =>
            {
                txtInfo.AppendText(msg + "\r\n");
            }));
        }
        protected void print(string format, params object[] arg)
        {
            this.Invoke(new Action(() =>
            {
                txtInfo.AppendText(string.Format(format, arg) + "\r\n");
            }));
        }
        #endregion

        #region >>Start<<
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            appStart();
        }

        protected override void Start(bool isStop)
        {
            if (isStop)
            {
                startToolStripMenuItem.Text = "Start";
                //timer1.Stop();
                print(DateTime.Now.ToString("[mm:dd:ss]") + " Stop");
            }
            else
            {
                startToolStripMenuItem.Text = "Stop";
                //timer1.Start();
                print(DateTime.Now.ToString("[mm:dd:ss]") + " Start");
            }
        }

        protected override void setAppInfo()
        {
            if (clientApp == null) return;

            clientApp.Info = new MSGGolbalInfo.UserInfo();

            clientApp.Info.Add(AppName, new MSGGolbalInfo.UserInfoItem(AppName));
            clientApp.Info[AppName].Add(Keys.Client.LocalMode, 500); //登入检查的标签,Level 值

            //跟服務器登記我是LoginServer的執行者
            clientApp.Info.Add(Keys.Execution, new MSGGolbalInfo.UserInfoItem(Keys.Execution));
            clientApp.Info[Keys.Execution].Add(Keys.Client.LoginServer, 500); //登入检查的标签,Level 值
            clientApp.Info[Keys.Execution].Add(Keys.JSON.LoginServer, 500); //登入检查的标签,Level 值

            //跟服務器登記我要監看user的登出
            clientApp.Info.Add(Keys.Watch, new MSGGolbalInfo.UserInfoItem(Keys.Watch));
            clientApp.Info[Keys.Watch].Add(Keys.Client.DEL, true);
            clientApp.Info[Keys.Watch].Add(Keys.JSON.DEL, true);

            if (clientApp.isStart)
                clientApp.setInfo();
        }

        protected override void clientApp_CommandReceivedEvent(object sender, EventArgs e)
        #region >><<
        {
            if (e is MSGGolbalInfo.ULogin)
            {
                ULogin args = (ULogin)e;
                args.IsResult = true;
                args.Success = true;

                Account acc = args.Acc;
                if (acc != null && !string.IsNullOrWhiteSpace(acc.UserName))
                {
                    User user1 = lstUser.Find(r => r.UserName.ToLower() == acc.UserName.ToLower() && r.Password == acc.Password);
                    if (user1 == null)
                    {
                        //不通過
                        print("[{0}] Login fail {1} - {2} - {3}", DateTime.Now.ToString("mm:dd:ss"), acc.UserName, acc.Password, args.APPName);
                    }
                    else
                    {
                        args.isLoginSuccess = true;
                        print("[{0}] Login {1} - {2} - {3}", DateTime.Now.ToString("mm:dd:ss"), acc.UserName, acc.Password, args.APPName);
                    }
                }
                else
                {
                    //不通過
                    print("[{0}] Login fail {1} - {2} - {3}", DateTime.Now.ToString("mm:dd:ss"), acc.UserName, acc.Password, args.APPName);
                }

                clientApp.SendData(TCPGolbalInfo.FlagEnum.Cmd, args);
            }
        }
        #endregion

        protected override void clientApp_ClientStateEvent(object sender, TCPGolbalInfo.FlagEnum flag)
        #region >><<
        {
            switch (flag)
            {
                case TCPGolbalInfo.FlagEnum.LoginOK:
                    print(DateTime.Now.ToString("[mm:dd:ss]") + " LoginOK");
                    setAppInfo();
                    break;
                case TCPGolbalInfo.FlagEnum.Logout: print(DateTime.Now.ToString("[mm:dd:ss]") + " Logout"); break;
                case TCPGolbalInfo.FlagEnum.LoginFail: print(DateTime.Now.ToString("[mm:dd:ss]") + " LoginFail"); break;
            }
        }
        #endregion

        protected override void clientApp_SettingEvent(object sender, EventArgs e)
        #region >><<
        {
            if (e is ActionArgs)
            {
                ActionArgs args = (ActionArgs)e;
                if (args.SysCmd is UserCommand)
                {
                    UserCommand cmd = args.SysCmd as UserCommand;
                    switch (cmd.ActCmd)
                    {
                        case MSGGolbalInfo.MSGEvent.ActionCommandEvent.Del:
                            List<MSGGolbalInfo.User> lst = cmd.Data as List<MSGGolbalInfo.User>;
                            if (lst != null && lst.Count > 0)
                            {
                                lst.ForEach(r =>
                                {
                                    print("[{0}] Logout {1} - {2} - {3}", DateTime.Now.ToString("mm:dd:ss"), r.UserName, r.EPoint, r.APPName);
                                });
                            }
                            break;
                    }
                }
            }
        }
        #endregion
        #endregion

        #region >>ServerIP Set<<
        private void serverToolStripMenuItem_Click(object sender, EventArgs e)
        {
            setSetverIP();
        }

        protected override void ServerIPset()
        {
            //if (clientApp == null || !clientApp.isStart) return;

        }
        #endregion

        #region >>LoadUser<<
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtAccount.Text = SaveUser(txtAccount.Lines);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtAccount.Text = LoadUser();
        }

        [Serializable]
        public class User
        {
            public string UserName { get; set; }
            public string Password { get; set; }
        }

        private List<User> lstUser = new List<User>();
        private OUtl.XMLDATAIO dataio = null;

        private string LoadUser()
        {
            string rtn = "";
            string f_user = "user.xml";
            string f_p = Directory.GetCurrentDirectory();

            dataio = new OUtl.XMLDATAIO("user", f_p, f_user, typeof(List<User>));
            object oo = dataio.Load();
            if (oo is List<User>)
            {
                lstUser = (List<User>)oo;
            }

            if (lstUser == null || lstUser.Count == 0)
            {
                lstUser.Add(new User() { UserName = "admin", Password = "admin" });
                lstUser.Add(new User() { UserName = "admin2", Password = "admin2" });
            }

            foreach (User user1 in lstUser)
            {
                rtn += user1.UserName + "," + user1.Password + "\r\n";
            }

            return rtn;
        }
        private string SaveUser(string[] txt)
        {
            string rtn = ""; ;
            lstUser.Clear();
            if (txt != null && txt.Length > 0)
            {
                foreach (string ss in txt)
                {
                    if (ss.Length == 0 || string.IsNullOrWhiteSpace(ss)) continue;
                    string ss1 = ss.Replace(" ", "").Replace("\r\n", "");

                    int ii1 = ss1.IndexOf(',');
                    if (ii1 < 2 || ii1 == ss1.Length) continue;
                    string ss2 = ss1.Substring(0, ii1);
                    string ss3 = ss1.Substring(ii1 + 1, ss1.Length - ii1 - 1);
                    lstUser.Add(new User()
                    {
                        UserName = ss2,
                        Password = ss3,
                    });
                }
            }

            if (dataio != null)
            {
                dataio.Save(lstUser);
            }

            if (lstUser == null || lstUser.Count == 0)
                lstUser.Add(new User() { UserName = "admin", Password = "admin" });

            foreach (User user1 in lstUser)
            {
                rtn += user1.UserName + "," + user1.Password + "\r\n";
            }

            return rtn;
        }

        #endregion      
    }
}
